package controllers

import (
	"beego-admin/services"
	"fmt"
	"log"
	"os"
	"path"
)

type AdminFileController struct {
	baseController
}

func (afc *AdminFileController) Index() {
	var adminUserService services.AdminUserService
	data, pagination := adminUserService.GetPaginateData(admin["per_page"].(int), gQueryParams)
	afc.Data["data"] = data
	afc.Data["paginate"] = pagination

	afc.Layout = "public/base.html"
	afc.TplName = "file/upload.html"
}

func (afc *AdminFileController) ShowUpload() {

	afc.Layout = "public/base.html"
	afc.TplName = "file/upload.html"
}
func (afc *AdminFileController) Upload() {
	log.Println("文件上传开始")
	f, h, err1 := afc.GetFile("file") //获取上传的文件
	if err1 != nil {
		fmt.Println("上传失败", err1)
		return
	}
	log.Println("文件大小", h.Size)
	ext := path.Ext(h.Filename)
	//验证后缀名是否符合要求
	var AllowExtMap map[string]bool = map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".bat":  true,
		".txt":  true,
		".docx":  true,
		".doc":  true,
		".xlsx":  true,
		".xls":  true,
		".pdf":  true,
		".zip":  true,
		".rar":  true,	
	}
	if _, ok := AllowExtMap[ext]; !ok {
		afc.Ctx.WriteString("后缀名不符合上传要求")
		return
	}

	//创建目录
	uploadDir := "static/file/"
	err := os.MkdirAll(uploadDir, 777)
	if err != nil {
		afc.Ctx.WriteString(fmt.Sprintf("%v", err))
		return
	}
	//构造文件名称
	fpath := uploadDir + h.Filename
	defer f.Close() //关闭上传的文件，不然的话会出现临时文件不能清除的情况
	err = afc.SaveToFile("file", fpath)
	if err != nil {
		afc.Ctx.WriteString(fmt.Sprintf("%v", err))
	}
	afc.Ctx.WriteString("上传成功~！！！！！！！")

	log.Println("文件上传结束")
}
func (afc *AdminFileController) ShowDownload() {

	afc.Layout = "public/base.html"
	afc.TplName = "file/upload.html"
}

func (afc *AdminFileController) Download() {
	log.Println("文件下载开始")
	file := afc.Ctx.Input.Query("name")
	fmt.Println("filename:", file)
	afc.Ctx.Output.Download("static/file/"+file, file)
	fmt.Println("文件下载结束")

}
